import Vue from "vue";
import VueRouter from "vue-router";
import store from "../store";

import NProgress from "nprogress";
import "nprogress/nprogress.css";

import axios from "axios";

const Login = () => import(/* webpackChunkName: "login" */ "views/login/index");
const Register = () =>
  import(/* webpackChunkName: "register" */ "views/register/index");
const Index = () => import(/* webpackChunkName: "index" */ "views/index/index");
const Admin = () => import(/* webpackChunkName: "admin" */ "views/admin/index");

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/index",
  },
  // 首页
  {
    path: "/index",
    name: "Index",
    component: Index,
    children: [
      // 图书馆页面
      {
        path: "/library",
        name: "Library",
        component: () => {
          return import(
            /* webpackChunkName: "library" */ "../views/library/index"
          );
        },
        meta: {
          requireAuth: true,
        },
      },
      // 随笔页面
      {
        path: "/jotters",
        name: "Jotters",
        meta: {
          requireAuth: true,
        },
        component: () => {
          return import(
            /* webpackChunkName: "jotters" */ "../views/jotters/index.vue"
          );
        },
      },
      // 随笔详情页面
      {
        path: "/jotters/:id",
        name: "JotterDetails",
        meta: {
          requireAuth: true,
        },
        component: () => {
          return import(
            /* webpackChunkName: "jotterDetails" */ "../views/jotter-details/index.vue"
          );
        },
      },
    ],
  },
  // 后台页面
  {
    path: "/admin",
    name: "Admin",
    component: Admin,
    meta: {
      requireAuth: true,
    },
    children: [
      // md编辑器页面
      {
        path: "/admin/article/editor",
        name: "Editor",
        component: () => {
          return import(
            /* webpackChunkName: "mdEditor" */ "../components/content/admin/AdminMdEditor"
          );
        },
        meta: {
          requireAuth: true,
        },
      },
    ],
  },
  // 登陆页面
  {
    path: "/login",
    name: "Login",
    component: Login,
  },
  // 注册页面
  {
    path: "/register",
    name: "Register",
    component: Register,
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

// 解决重复路由报错
const originalPush = VueRouter.prototype.push;
// 修改原型对象中的 push 方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

// 前置导航守卫
router.beforeEach((to, from, next) => {
  // 开启进度条
  NProgress.start();
  // 判断请求是否需要登陆
  if (to.meta.requireAuth) {
    // 如果已有用户登陆
    if (store.state.user) {
      return axios
        .get("/test")
        .then((res) => {
          console.log(res);
          next();
        })
        .catch((err) => {
          console.log(err);
          next({
            path: "/login",
            // 此参数作为完成登陆之后的跳转路径
            query: { redirect: to.fullPath },
          });
        });
    }
    // 没有用户登陆，跳转到登陆页
    else {
      return next({
        path: "/login",
        // 此参数作为完成登陆之后的跳转路径
        query: { redirect: to.fullPath },
      });
    }
  }
  // 不需登陆就可以访问
  return next();
});

// 后置导航守卫
router.afterEach(() => {
  NProgress.done();
});

// 格式化菜单路由
export function formatRoutes(routes) {
  let fmtRoutes = [];
  routes.forEach((route) => {
    if (route.children) {
      route.children = formatRoutes(route.children);
    }

    let fmtRoute = {
      path: route.path,
      component: (resolve) =>
        require([`@/${route.component}` + ".vue"], resolve),
      name: route.name,
      nameZh: route.nameZh,
      iconCls: route.iconCls,
      meta: {
        requireAuth: true,
      },
      children: route.children,
    };
    fmtRoutes.push(fmtRoute);
  });
  return fmtRoutes;
}

/**
 * 在router/index.js中定义$addRoutes,调用这个方法来添加路由，这个方法会先重置路由
 * 这个路由只会包括非权限页，比如登录页，再调用router.addRoutes添加权限路由，
 * 此方法亲测，完美解决，方法来自GitHub的issues,https://github.com/vuejs/vue-router/issues/2886
 */
router.$addRoutes = (params) => {
  router.matcher = new VueRouter({
    mode: "history",
    base: process.env.BASE_URL,
    // 重置路由规则
    routes,
  }).matcher;
  router.addRoutes(params); // 添加路由
};

/**
 * onReady方法可以看官方文档，不赘述了
 */
router.onReady(() => {
  if (store.state.user) {
    router.addRoutes(formatRoutes(store.state.menuList)); // 添加动态路由,这里不必用$addRoutes，因为刷新后就没有上一次的动态路由，故不必清除
  }
});

export default router;
